package com.yyaccp.easybuy.security.service.token;

import com.yyaccp.easybuy.security.vo.AuthProperties;
import com.yyaccp.easybuy.security.vo.LoginUser;
import com.yyaccp.easybuy.security.vo.Token;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.Base64UrlCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TokenServiceJwtImpl implements TokenService {
    private static final String JWT_SECRET = Base64UrlCodec.BASE64.encode("12@aH.a");
    @Autowired
    private AuthProperties authProperties;

    public Token createToken(LoginUser loginUser) {
        List<String> roles = loginUser.getRoles();
        List<String> perms = loginUser.getPerms();
        Map<String, Object> map = new HashMap<>();
        if("url".equals(authProperties.getMode())) {
            map.put("urls", loginUser.getUrls());
        } else {
            map.put("roles", roles);
            map.put("perms", perms);
        }
        map.put("username", loginUser.getUsername());
        // 生成JWT
        String jwt = Jwts.builder().setClaims(map).signWith(SignatureAlgorithm.HS512, JWT_SECRET).compact();
        return new Token(jwt, loginUser.getUsername(), System.currentTimeMillis(), System.currentTimeMillis() + 600 * 1000);
    }

    public LoginUser getLoginUser(String token) {
        Assert.hasText(token, "token不能为空");
        token = token.replace("Bearer ", "");
        // 解析JWT的payload
        Claims claims = Jwts.parser().setSigningKey(JWT_SECRET).parseClaimsJws(token).getBody();
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername((String) claims.get("username"));
        if("url".equals(authProperties.getMode())) {
            loginUser.setUrls((List<String>) claims.get("urls"));
        } else {
            loginUser.setRoles((List<String>) claims.get("roles"));
            loginUser.setPerms((List<String>) claims.get("perms"));
        }
        return loginUser;
    }

    @Override
    public void deleteToken(String token) {
        System.err.println("无法删除无状态token：" + token);
    }
}
